package com.maybach.web.controller.logistics;

import com.maybach.common.BizResult;
import com.maybach.common.enums.ActLogActorNameEnum;
import com.maybach.common.enums.ActLogBizTypeEnum;
import com.maybach.common.enums.order.LogisticsStatusEnum;
import com.maybach.common.model.LogisticsCompanyDO;
import com.maybach.core.ao.*;
import com.maybach.core.form.carFormalities.CarFormalitiesForm;
import com.maybach.core.form.logistics.LogisticsCompanyForm;
import com.maybach.core.form.logistics.LogisticsCompanyQueryForm;
import com.maybach.core.form.shippingCar.DeliveryCarForm;
import com.maybach.core.form.shippingCar.LogisticsInfoForm;
import com.maybach.util.query.support.PageResult;
import com.maybach.web.constants.WebConstants;
import com.maybach.web.framework.util.WebUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * Created by weishuai on 16/2/23.
 */

@Controller
@RequestMapping("/logistics/")
public class LogisticsCompanyController {
    @Autowired
    LogisiticsCompanyAO logisiticsCompanyAO;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    CarFormalitiesAO carFormalitiesAO;

    @Autowired
    ShippingCarsAO shippingCarsAO;

    @Autowired
    LoanOrderAO loanOrderAO;
    @Autowired
    ActLogAO actLogAO;


    /**
     * 列表页面
     *
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "list")
    public String list(@Valid LogisticsCompanyQueryForm queryForm, BindingResult bindingResult, ModelMap model) {
        if (null == queryForm) {
            queryForm = new LogisticsCompanyQueryForm();
        }
        if (!model.containsAttribute("logisticsCompanyQueryForm")) {
            model.addAttribute(queryForm);
        }

        PageResult<LogisticsCompanyDO> result = logisiticsCompanyAO.queryLogisticsCompany(queryForm);
        model.addAttribute("pageResult", result);
        return "logistics/companyList";
    }

    /**
     * 添加页面
     *
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "add")
    public String add(@RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        if (!model.containsAttribute("logisticsCompanyForm")) {
            LogisticsCompanyForm logisticsCompanyForm = new LogisticsCompanyForm();
            model.addAttribute(logisticsCompanyForm);
        }
        return "logistics/add";
    }


    /**
     * 编辑页面
     *
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "edit")
    public String edit(@RequestParam(value = "id") Long id, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);

        LogisticsCompanyForm logisticsCompanyForm = logisiticsCompanyAO.getLogisticsCompanyFormById(id);
        model.addAttribute(logisticsCompanyForm);
        return "logistics/add";
    }

    @RequiresAuthentication
    @RequestMapping(value = "doUpdate", method = RequestMethod.POST)
    public String doUpdate(@Valid LogisticsCompanyForm logisticsCompanyForm, BindingResult bindingResult, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);

        if (bindingResult.hasErrors()) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        try {
            actLogAO.addLog(ActLogBizTypeEnum.Other,logisticsCompanyForm.getId(),"编辑物流公司", ActLogActorNameEnum.updateLogisticsCompany);

            logisiticsCompanyAO.updateLogisticsCompany(logisticsCompanyForm);
            logger.debug("update logisticsCompany id={}", logisticsCompanyForm.getId());
        } catch (Exception e) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }


        return "result";
    }


    @RequiresAuthentication
    @RequestMapping(value = "doAdd", method = RequestMethod.POST)
    public String doAdd(@Valid LogisticsCompanyForm logisticsCompanyForm, BindingResult bindingResult, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);

        if (bindingResult.hasErrors()) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        try {

            Long id = logisiticsCompanyAO.addLogisticsCompany(logisticsCompanyForm);
            logger.debug("add logisticsCompany id={}", id);
            actLogAO.addLog(ActLogBizTypeEnum.Other,id,"增加物流公司", ActLogActorNameEnum.addLogisticsCompany);
        } catch (Exception e) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }

        return "result";
    }

    /**
     * 车辆手续初始化
     * @param outOrderId
     * @param redirectUrl
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "carFormalityEdit")
    public String editCarFormalities(@RequestParam(value = "outOrderId") Long outOrderId,@RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl,ModelMap model){
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);

        CarFormalitiesForm carFormalitiesForm = carFormalitiesAO.getByOutOrderId(outOrderId);
        carFormalitiesForm.setOutOrderId(outOrderId);
        model.addAttribute(carFormalitiesForm);
        return "loanOrder/edit/carFormalityEdit";

    }

    /**
     * 编辑界面--交车信息
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "deliveryCarsEdit" )
    public String editDeliveryCars(Long outOrderId,@RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl,ModelMap model){
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);

        DeliveryCarForm deliveryCarForm=shippingCarsAO.getByOutOrderId(outOrderId);
        deliveryCarForm.setOuterOrderId(outOrderId);
        model.addAttribute(deliveryCarForm);
        return "loanOrder/edit/deliveryCarsEdit";
    }
    /**
     * 编辑交车信息
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "doEditDeliveryCars" , method = RequestMethod.POST)
    public String doEditDeliveryCars(@Valid DeliveryCarForm deliveryCarForm,@RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl,ModelMap model){
        actLogAO.addLog(ActLogBizTypeEnum.LoanOrder,deliveryCarForm.getOuterOrderId(),"编辑交车信息", ActLogActorNameEnum.updateDeliveryCar);
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        shippingCarsAO.updateDeliveryCar(deliveryCarForm);
        return getDetailString(deliveryCarForm.getOuterOrderId());
    }
    /**
     * 新增交车信息
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "doAddDeliveryCars")
    public String doAddDeliveryCars(@Valid DeliveryCarForm deliveryCarForm,@RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl,ModelMap model){
        actLogAO.addLog(ActLogBizTypeEnum.LoanOrder,deliveryCarForm.getOuterOrderId(),"增加交车信息", ActLogActorNameEnum.addDeliveryCar);

        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        shippingCarsAO.addDeliveryCar(deliveryCarForm);
        return getDetailString(deliveryCarForm.getOuterOrderId());
    }

    /**
     * 编辑车辆手续信息
     * @param carFormalitiesForm
     * @param redirectUrl
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "doEditCarFormalities")
    public String doEditCarFormalities(@Valid CarFormalitiesForm carFormalitiesForm, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        actLogAO.addLog(ActLogBizTypeEnum.LoanOrder,carFormalitiesForm.getOutOrderId(),"编辑车辆手续", ActLogActorNameEnum.updateCarFormalities);
        carFormalitiesAO.updateCarFormalities(carFormalitiesForm);
        return getDetailString(carFormalitiesForm.getOutOrderId());
    }


    /**
     * 新增车辆手续信息
     * @param carFormalitiesForm
     * @param redirectUrl
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "doAddCarFormalities")
    public String doAddCarFormalities(@Valid CarFormalitiesForm carFormalitiesForm, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        actLogAO.addLog(ActLogBizTypeEnum.LoanOrder,carFormalitiesForm.getOutOrderId(),"新增车辆手续", ActLogActorNameEnum.addCarFormalities);
        carFormalitiesAO.addCarFormalities(carFormalitiesForm);
        return getDetailString(carFormalitiesForm.getOutOrderId());
    }

    /**
     * 编辑物流初始化页面
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "logisticsInfoEdit")
    public String editLogisticsInfo(Long outOrderId,@RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl,ModelMap model){

        LogisticsInfoForm logisticsInfoForm=new LogisticsInfoForm();
        logisticsInfoForm=shippingCarsAO.getLogisticsInfoByOutOrderId(outOrderId);
        logisticsInfoForm.setOuterOrderId(outOrderId);
        model.addAttribute(logisticsInfoForm);
        model.put("ls",logisiticsCompanyAO.getAllLogisticsCompany(LogisticsStatusEnum.normal));
        return "loanOrder/edit/logisticsInfoEdit";
    }


    /**
     * 编辑物流信息
     * @param logisticsInfoForm
     * @param redirectUrl
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "doEditLogisticsInfo")
    public String doEditLogisticsInfo(@Valid LogisticsInfoForm logisticsInfoForm, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        actLogAO.addLog(ActLogBizTypeEnum.LoanOrder,logisticsInfoForm.getOuterOrderId(),"编辑物流信息", ActLogActorNameEnum.updateLogisticsInfo);

        shippingCarsAO.updateLogisticsInfo(logisticsInfoForm);
            return getDetailString(logisticsInfoForm.getOuterOrderId());

    }

    /**
     * 增加物流信息
     * @param logisticsInfoForm
     * @param redirectUrl
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "doAddLogisticsInfo")
    public String doAddLogisticsInfo(@Valid LogisticsInfoForm logisticsInfoForm, @RequestParam(required = false, value = WebConstants.REDIRECT_URL_KEY) String redirectUrl, ModelMap model) {
        actLogAO.addLog(ActLogBizTypeEnum.LoanOrder,logisticsInfoForm.getOuterOrderId(),"新增物流信息", ActLogActorNameEnum.addLogisticsInfo);

        shippingCarsAO.addLogisticsInfo(logisticsInfoForm);
        return getDetailString(logisticsInfoForm.getOuterOrderId());
    }



    /**
     * 新增、修改、成功挑战到订单宝详情
     * @param outOrderId
     * @return
     */
    private String getDetailString(Long outOrderId) {
        String detail = WebConstants.REDIRECT_PREFIX+"/loanOrder/detail/"+outOrderId;
        return detail;
    }


    @ResponseBody
    @RequiresAuthentication
    @RequestMapping(value = "doUpdateStatus.json")
    public BizResult doUpdateStatus(@RequestParam(value = "status") Integer status, @RequestParam(value = "id") Long id) {
        actLogAO.addLog(ActLogBizTypeEnum.LoanOrder,id,"编辑物流公司状体", ActLogActorNameEnum.updateLogisticsCompanyStatus);

        return logisiticsCompanyAO.updateStatus(id, status);
    }
}
